package ch12.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import oracle.net.aso.b;

public class FileCopyer {
	
	public void copy(String src,String desc) {

		File f1 = new File(src);
		File f2 = new File(desc);
		copy(f1, f2);
	}
	
	//使用方法重载对参数进行重构
	public void copy(File srcFile,File descFile) {
		//如果源文件不存在，则不需要拷贝
		if(srcFile==null||!srcFile.exists()) {
			System.out.println("源文件不存在");
			return;
		}
		//检查目标文件或目标目录是否存在
		if(descFile==null) {
			System.out.println("目标文件为null");
			return;
		}else {
			descFile.getParentFile().mkdirs();
		}
	
		//输入流和输出流
		FileInputStream fileInputStream = null;
		
		FileOutputStream fileOutputStream = null;
		
		try {
			fileInputStream = new FileInputStream(srcFile);
			fileOutputStream = new FileOutputStream(descFile);
			
			byte[] b = new byte[1024*1024];
			//把读到的数据保存到buffer中，并返回实际读取的内容长度，如果文件已经读取完毕，则返回-1
			int length = fileInputStream.read(b);
		
			while(length!=-1) {//当length==-1时，表示文件读取完毕
				//循环写入数据，直到文件写完为止；注意：每次只写入读取的数据0，length
			   fileOutputStream.write(b,0,length);
			   
			   //循环读取数据，直到文件读完为止
			   length = fileInputStream.read(b);
			
			}
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(fileInputStream!=null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fileOutputStream!=null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	public static void main(String[] args) {
		String src = "D:\\oracle6.zip";
		String desc = "D:\\ww\\2业点1.zip";
		
		FileCopyer copyer = new FileCopyer();
		System.out.println("拷贝文件.............");
		long start = System.currentTimeMillis();
		copyer.copy(src, desc);
		long stop = System.currentTimeMillis();
		
		System.out.println("拷贝时间:"+((stop-start)/1000));
	
		
	}

}
